<?php
/**
 * Created by PhpStorm.
 * User: chentairen
 * Date: 2017/11/16
 * Time: 上午10:49
 */

namespace App\Service;

use App\Common\Model\ShopAccount;
use App\Model\Address;
use App\Model\Goods;
use App\Model\Scores;
use App\Traits\ErrorTrait;
use Illuminate\Support\Facades\DB;

class ShopService
{
    use ErrorTrait;

    public $sendStatus = [
        0 => '待发货',
        1 => '已发货'
    ];

    public function getGoodsList($scores, int $level, int $start, int $limit)
    {
        $goodsList = Goods::filterByLevel($level)->online()
            ->select('id', 'goods_name', 'scores', 'cover')
            ->orderBy('scores', $scores)
            ->offset($start)->limit($limit)
            ->get()->toArray();
        return $goodsList;
    }

    /**
     * 获取商品条数
     * @param int $scores
     * @param int $level
     * @return mixed
     */
    public function getGoodsNum(int $level)
    {
        $num = Goods::filterByLevel($level)->online()->count();
        return $num;
    }

    /**
     * 获得用户积分
     * @param int $uid
     * @return mixed
     */
    public function getScores(int $uid)
    {
        return DB::table('scores')->where('uid', $uid)->sum('bill');
    }

    /**
     * 获取商品详情
     * @param $goodsId
     * @return mixed
     */
    public function getGoodsInfo($goodsId)
    {
        $goods = Goods::leftJoin('goods_info', 'goods_info.goods_id', '=', 'goods.id')
            ->select('goods.id', 'goods_name', 'scores', 'market_price', 'freight', 'goods_info.banner', 'goods_info.goods_info', 'instructions')
            ->where('goods.id', $goodsId)
            ->first();
        $goods->banner = json_decode($goods->banner);
        return $goods;
    }

    /**
     * 获取订单页面确认信息
     * @param $uid
     * @param $goodsId
     * @param $addressId
     * @return array
     */
    public function getConfirmOrderInfo($uid, $goodsId, $addressId)
    {
        $addressModel = new Address();
        if ($addressId) {
            $address = $addressModel->getAddress($addressId);
        } else {
            $address = $addressModel->getDefaultAddress($uid);
        }
        $goods = Goods::leftJoin('goods_info', 'goods_info.goods_id', '=', 'goods.id')
            ->select('goods.id', 'goods_name', 'scores', 'market_price', 'freight', 'goods_info.banner')
            ->where('goods.id', $goodsId)
            ->first();
        $userScores = Scores::where('uid', $uid)->sum('bill');
        return [
            'address_id' => $address->id,
            'receiver' => $address->receiver,
            'phone' => $address->phone,
            'address' => $address->area . ' ' . $address->address,
            'goods_id' => $goods->id,
            'goods_banner' => json_decode($goods->banner)[0],
            'goods_name' => $goods->goods_name,
            'goods_scores' => $goods->scores,
            'goods_price' => $goods->market_price,
            'freight' => $goods->freight,
            'user_scores' => $userScores
        ];
    }

    /**
     * 创建订单
     * @param $uid
     * @param $goodsId
     * @param $amount
     * @param $addressId
     */
    public function createOrder($uid, $goodsId, $amount, $addressId)
    {
        $addressModel = new Address();
        $address = $addressModel->getAddress($addressId);
        $goods = Goods::where('id', $goodsId)->first();
        $userScores = $this->getScores($uid);
        if ($userScores < $goods->scores * $amount) {
            $this->error = '用户积分不足';
            return false;
        }
        // 创建订单主表信息
        $orderInsert = [
            'uid' => $uid,
            'order_no' => date('ymdHis').mt_rand(100, 999),
            'area' => $address['area'],
            'address' => $address['address'],
            'receiver' => $address['receiver'],
            'receiver_tel' => $address['phone'],
            'scores' => $goods->scores * $amount,
            'freight' => $goods->freight,
            'pay_status' => 1,
            'send_status' => 0,
            'create_time' => time()
        ];
        // 生成订单附表信息
        $orderInfoInsert = [
            'uid' => $uid,
            'goods_id' => $goodsId,
            'goods_name' => $goods->goods_name,
            'num' => $amount,
            'scores' => $goods->scores * $amount,
            'coupon' => 0
        ];
        // 扣除用户积分
        $scoresInsert = [
            'uid' => $uid,
            'bill' => -($goods->scores * $amount),
            'remark' => '购买'.$goods->goods_name.'X'.$amount.'积分抵扣',
            'create_time' => time()
        ];
        DB::beginTransaction();
        $re = DB::update('update aixin_goods set `rest`=`rest`-?,`sale`=`sale`+?  where id = ? and `rest` >= ?', [$amount, $amount, $goodsId, $amount]);
        if ($re == 0) {
            DB::rollBack();
            $this->error = '库存不足';
            return false;
        }
        $orderId = DB::table('order')->insertGetId($orderInsert);
        if (!$orderId) {
            DB::rollBack();
            $this->error = '参数错误';
            return false;
        }

        $orderInfoInsert['order_id'] = $orderId;
        $scoresInsert['order_id'] = $orderId;

        $re = DB::table('order_info')->insert($orderInfoInsert);
        if (!$re) {
            DB::rollBack();
            $this->error = '参数错误';
            return false;
        }
        $re = DB::table('scores')->insert($scoresInsert);
        if (!$re) {
            DB::rollBack();
            $this->error = '参数错误';
            return false;
        }
        DB::commit();
        return $orderId;

    }

    /**
     * 订单详情
     * @param $orderId
     * @param int $uid
     * @return array
     */
    public function getOrderDetail($orderId, $uid = 0)
    {
        $where = [['id', '=', $orderId]];
        $infoWhere = [['order_id', '=', $orderId]];
        if ($uid) {
            $where[] = ['uid', '=', $uid];
            $infoWhere[] = ['uid', '=', $uid];
        }
        $order = DB::table('order')->where($where)->first();
        $orderInfo = DB::table('order_info')->leftJoin('goods', 'goods.id', '=', 'order_info.goods_id')
            ->select('order_info.*', 'goods.cover')->where($infoWhere)->first();
        $return = [
            'goods_pic' => $orderInfo->cover,
            'goods_name' => $orderInfo->goods_name,
            'goods_scores' => $orderInfo->scores / $orderInfo->num,
            'goods_num' => $orderInfo->num,
            'total_scores' => $order->scores,
            'create_time' => date('Y-m-d H:i:s', $order->create_time),
            'order_no' => $order->order_no,
            'receiver' => $order->receiver,
            'address' => $order->area . $order->address,
            'phone' => $order->receiver_tel,
            'send_status' => $this->sendStatus[$order->send_status],
            'send_company' => $order->send_company,
            'send_no' => $order->send_no
        ];
        return $return;

    }

    public function addGoods($param)
    {
        $now = time();
        $goodsInsert = [
            'goods_name' => $param['goods_name'],
            'scores' => $param['scores'],
            'market_price' => $param['market_price'],
            'allow_level' => '',
            'cover' => $param['cover'],
            'status' => $param['status'],
            'freight' => $param['freight'],
            'rest' => $param['rest'],
            'sale' => 0,
            'is_del' => 1,
            'create_time' => $now
        ];
        $goodsInfoInsert = [
            'banner' => json_encode($param['banner']),
            'goods_info' => $param['goods_info'],
            'instructions' => $param['instructions'],
            'create_time' => $now
        ];
        $id = DB::table('goods')->insertGetId($goodsInsert);
        if (!$id) {
            $this->error = '参数错误';
            return false;
        }
        $goodsInfoInsert['goods_id'] = $id;
        DB::table('goods_info')->insert($goodsInfoInsert);
        return true;
    }

    public function updateGoods($param)
    {
        if (!$param['id']) {
            $this->error = '缺少参数';
            return false;
        }
        $now = time();
        $goodsUpdate = [
            'goods_name' => $param['goods_name'],
            'scores' => $param['scores'],
            'market_price' => $param['market_price'],
            'cover' => $param['cover'],
            'status' => $param['status'],
            'freight' => $param['freight'],
            'rest' => $param['rest'],
            'update_time' => $now
        ];
        $goodsInfoUpdate = [
            'banner' => json_encode($param['banner']),
            'goods_info' => $param['goods_info'],
            'instructions' => $param['instructions'],
            'update_time' => $now
        ];
        $re = DB::table('goods')->where('id', $param['id'])->update($goodsUpdate);
        if (!$re) {
            $this->error = '参数错误';
            return false;
        }
        DB::table('goods_info')->where('goods_id', $param['id'])->update($goodsInfoUpdate);
        if (!$re) {
            $this->error = '参数错误';
            return false;
        }
        return true;
    }

}